<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-button type="primary" @click="addRoles">添加角色</el-button>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data='rolesList' border stripe resizable>
        <el-table-column type="expand">
          <template slot-scope="scoped">
            <el-row class="bdtop vcenter" v-for="(item) in scoped.row.children" :key="item.id">
              <!-- 一级权限的渲染 -->
              <el-col :span="5">
                <el-tag @close="handleClose(item,scoped.row)" closable> {{item.authName}} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限的渲染 -->
              <el-col :span="19">
                <!-- 通过for循环渲染二级权限 -->
                <el-row v-for="items in item.children" :key="items.id" class="vcenter bdtops">
                  <el-col  :span="6">
                    <el-tag @close="handleClose(items,scoped.row)" type="success" closable>{{items.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag @close="handleClose(item2,scoped.row)" type="warning" closable v-for="item2 in items.children" :key="item2.id">
                      {{item2.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="roleName" label="名称" align="center"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scoped">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scoped.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(scoped.row.id)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRightDialog(scoped.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹出窗主体 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="30%" :model="ruleForm" @close='a'>
      <!-- 添加角色弹出窗内容 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <!-- 添加角色角色名称 -->
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="ruleForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <!-- 添加角色角色描述 -->
        <el-form-item label="角色描述">
          <el-input v-model="ruleForm.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加角色弹出窗底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色弹出窗主体 -->
    <el-dialog title="修改角色" :visible.sync="dialogVisibleto" width="30%" :model="ruleForm">
      <!-- 编辑角色弹出窗内容 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormto" label-width="100px" class="demo-ruleForm">
        <!-- 编辑角色角色名称 -->
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="ruleForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <!-- 编辑角色角色描述 -->
        <el-form-item label="角色描述">
          <el-input v-model="ruleForm.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <!-- 编辑角色弹出窗底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleto = false">取 消</el-button>
        <el-button type="primary" @click="addListto">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出窗 主体-->
    <el-dialog title="分配权限" :visible.sync="setVisible" width="30%" >
      <!-- 分配权限弹出窗内容 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox default-expand-all node-key='id' ref="treeRef" :default-checked-keys='defKeys'></el-tree>
      <!-- 分配权限弹出窗底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色的数据
      rolesList: [],
      setRolseList: [],
      dialogVisible: false,
      dialogVisibleto: false,
      setVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形图属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 修改或者添加调用的对象
      ruleForm: {
        // 角色名称
        roleName: '',
        // 角色描述
        roleDesc: '',
        name: ''
      },
      // 表单的验证规则
      rules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 默认是否选中
      defKeys: [],
      // 选中id
      rolesId: Number
    }
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 打开窗口
    addRoles () {
      console.log(this.$refs.ruleForm)
      this.dialogVisible = true
    },
    // 添加用户
    addList () {
      this.$refs.ruleForm.validate(async (val) => {
        if (val) {
          const { data: res } = await this.$http.post('roles', this.ruleForm)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          console.log(res)
          this.$message.success(res.meta.msg)
          this.getRolesList()
          this.dialogVisible = false
        }
      })
    },
    // 点击修改用户
    async showEditDialog (id, name) {
      this.dialogVisibleto = true
      console.log(id, name)
      console.log('roles' + id + 'roleName/' + name)
      const { data: res } = await this.$http.get('roles/' + id)
      this.ruleForm = res.data
      console.log(this.ruleForm)
    },
    a () {
      this.$refs.ruleForm.resetFields()
    },
    // 修改用户
    addListto () {
      this.$refs.ruleFormto.validate(async (val) => {
        if (val) {
          await this.$http.put('roles/' + this.ruleForm.roleId, {
            roleName: this.ruleForm.roleName
          })
          this.dialogVisibleto = false
          this.getRolesList()
          this.$message.success('修改成功')
        } else {
          this.$message.error('格式错误')
        }
      })
    },
    // 删除用户
    async del (id) {
      const a = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      console.log(a)
      if (a === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + id)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRolesList()
        this.$message.success('删除成功')
      }
    },
    // 根据id删除对应的权限
    async handleClose (id, ids) {
      const conf = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (conf === 'confirm') {
        const { data: res } = await this.$http.delete(
          `roles/${ids.id}/rights/${id.id}`
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        ids.children = res.data
      }
    },
    // 展开分配权限
    async showRightDialog (roles) {
      // 获取当前角色的id
      this.rolesId = roles.id
      console.log(this.rolesId)
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      this.rightsList = res.data
      // 清空this.defKeys数组
      this.defKeys = []
      // 调用递归获取id
      this.getLeafkeys(roles, this.defKeys)
      this.setVisible = true
      console.log(this.defKeys)
    },
    // 通过递归获取角色下的所有id
    getLeafkeys (node, arr) {
      // 如果node节点不含children属性的话则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafkeys(item, arr)
      })
    },
    // 点击为角色分配权限
    async allotRights () {
      let keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      keys = keys.join(',')
      console.log(keys)
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, {
        rids: keys
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      console.log(res)
      this.getRolesList()
      this.setVisible = false
    }
  },
  mounted () {
    this.getRolesList()
  }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 7px;
}
.bdtop:nth-child(1) {
  border-top: 1px solid #eee;
}
.bdtop {
  border-bottom: 1px solid #eee;
}
.bdtops {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
